﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.APP_UI.Common;
using KPIS.GERP.GBMS.MODEL;
using Telerik.Web.UI;
using KPIS.DBM;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class Copy_Bgm_Request : System.Web.UI.Page
    {
        Request_BLL req = new Request_BLL();
        ComboBLL combo = new ComboBLL();
        Main main = new Main();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtBgmYear.Text = Request.QueryString["year"];
                txtBgmYearOld.Value = txtBgmYear.Value - 1;
                lblJobSiteSeq.Text = Request.QueryString["id"];

                if (lblJobSiteSeq.Text.Length > 0)
                {
                    lblJobSiteName.Text = combo.JobsiteInfo(Convert.ToInt32(lblJobSiteSeq.Text)).Rows[0]["job_site_name"].ToString();
                }

                //LoadDDLBgmSource();
                LoadGridProject();
            }
        }

        //protected void LoadDDLBgmSource()
        //{
        //    ddlBgmSourceSeq.DataSource = combo.ListSourceCombo();
        //    ddlBgmSourceSeq.DataBind();

        //    main.InsertEmptyDDLAll(ddlBgmSourceSeq);

        //    if (ddlBgmSourceSeq.Items.Count > 1)
        //    {
        //        ddlBgmSourceSeq.SelectedIndex = 1;
        //    }
        //}

        protected void LoadGridProject()
        {
            //string strBgmSourceSeq = ddlBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strBgmYearOld = txtBgmYearOld.Text;
            string strJobSiteSeq = lblJobSiteSeq.Text;

            gridProject.DataSource = req.GetDataProjectByYearAndJobSite(strBgmYearOld, strJobSiteSeq, "", "A");
            gridProject.DataBind();
        }

        protected void ddlBgmSourceSeq_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadGridProject();
        }

        protected void txtBgmYearOld_TextChanged(object sender, EventArgs e)
        {
            LoadGridProject();
        }

        protected void btnPopupSave_Click(object sender, EventArgs e)
        {
            string strBgmYear = txtBgmYear.Text;
            string strBgmYearOld = txtBgmYearOld.Text;
            string strJobSiteSeq = lblJobSiteSeq.Text;
            int nDefYear = Convert.ToInt32(strBgmYear) - Convert.ToInt32(strBgmYearOld);
            IDBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

            if (strBgmYear.Length < 4)
            {
                main.MessageAlert(Page, "กรุณากรอกข้อมูล [ปีปัจจุบัน]");
                return;
            }
            else if (strBgmYearOld.Length < 4)
            {
                main.MessageAlert(Page, "กรุณากรอกข้อมูล [ปีที่คัดลอก]");
                return;
            }

            try
            {
                dbManager.Open();
                dbManager.BeginTransaction();

                foreach (GridDataItem item in gridProject.SelectedItems)
                {
                    string strBgmReqSeqOld = main.WebString(item["Sequence"].Text);
                    string strEmpSeq = new SsMng().GetUss(SsMng.SsUserType.EmpSeq);
                    string strSQL = "";

                    strSQL = "select r.bgm_req_seq as Sequence"
                        + ", r.bgm_req_code as bgm_prj_code, r.bgm_req_name as bgm_prj_name"
                        + ", r.bgm_req_descr as bgm_prj_descr, r.bgm_req_manager as bgm_prj_manager, r.bgm_req_scope as bgm_prj_scope"
                        + ", r.bgm_req_date as bgm_prj_date, r.bgm_req_reason as bgm_prj_reason, r.bgm_req_object as bgm_prj_object"
                        + ", r.bgm_req_target as bgm_prj_target, r.bgm_req_plan as bgm_prj_plan, r.bgm_req_remark as bgm_prj_remark"
                        + ", s.bgm_strat_list_name, j.job_site_name, jm.job_site_name as job_site_name_main"
                        + ", r.bgm_year, r.bgm_strat_list_seq, r.job_site_seq, r.job_site_seq_main"
                        + ", s.bgm_strat_list_name, ms.bgm_scope_name"
                        + ", r.prj_type_seq, r.date_start, r.date_end, pt.prj_type_name, r.record_status"
                        + ", re.total_amount, null as gfmis_code"
                        + " from bgm_request r"
                        + " left join bgm_strategy_data_list s on r.bgm_strat_list_seq = s.bgm_strat_list_seq"
                        + " left join hrm_mp_job_sites j on r.job_site_seq = j.job_site_seq"
                        + " left join hrm_mp_job_sites jm on r.job_site_seq_main = jm.job_site_seq"
                        + " left join bgm_mas_scopes ms on r.bgm_req_scope = ms.bgm_scope_seq"
                        + " left join bgm_mas_project_type pt on pt.prj_type_seq = r.prj_type_seq"
                        + " left join (select bgm_req_seq"
                            + ", sum(coalesce(total_amount, 0)) as total_amount"
                            + " from bgm_request_expense"
                            + " group by bgm_req_seq"
                            + ") re on r.bgm_req_seq = re.bgm_req_seq"

                        + " where r.bgm_req_seq = " + strBgmReqSeqOld;

                    DataTable dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                    
                    if (dtb.Rows.Count > 0)
                    {
                        string strBgmReqSeq = "";
                        DataRow dr = dtb.Rows[0];
                        
                        dbManager.CreateParameters(20);
                        dbManager.AddParameters(0, "@bgm_req_code", main.DBString(dr["bgm_prj_code"].ToString()));
                        dbManager.AddParameters(1, "@bgm_req_name", main.DBString(dr["bgm_prj_name"].ToString()
                            .Replace(strBgmYearOld, strBgmYear).Replace((Convert.ToInt32(strBgmYearOld) - 543).ToString(), (Convert.ToInt32(strBgmYear) - 543).ToString())));
                        dbManager.AddParameters(2, "@bgm_req_descr", main.DBString(dr["bgm_prj_descr"].ToString()));
                        dbManager.AddParameters(3, "@bgm_req_manager", main.DBString(dr["bgm_prj_manager"].ToString()));
                        dbManager.AddParameters(4, "@bgm_req_scope", main.DBString(dr["bgm_prj_scope"].ToString()));
                        dbManager.AddParameters(5, "@bgm_req_date", main.ConvertNullDateTime(dr["bgm_prj_date"]));
                        dbManager.AddParameters(6, "@bgm_req_reason", main.DBString(dr["bgm_prj_reason"].ToString()));
                        dbManager.AddParameters(7, "@bgm_req_object", main.DBString(dr["bgm_prj_object"].ToString()));
                        dbManager.AddParameters(8, "@bgm_req_target", main.DBString(dr["bgm_prj_target"].ToString()));
                        dbManager.AddParameters(9, "@bgm_req_plan", main.DBString(dr["bgm_prj_plan"].ToString()));
                        dbManager.AddParameters(10, "@bgm_req_remark", main.DBString(dr["bgm_prj_remark"].ToString()));
                        dbManager.AddParameters(11, "@bgm_strat_list_seq", main.DBString(dr["bgm_strat_list_seq"].ToString()));
                        dbManager.AddParameters(12, "@prj_type_seq", main.DBString(dr["prj_type_seq"].ToString()));
                        dbManager.AddParameters(13, "@job_site_seq", main.DBString(dr["job_site_seq"].ToString()));
                        dbManager.AddParameters(14, "@job_site_seq_main", main.DBString(dr["job_site_seq_main"].ToString()));
                        dbManager.AddParameters(15, "@bgm_year", main.DBString(strBgmYear));
                        DateTime? dtStart = (!string.IsNullOrEmpty(dr["date_start"].ToString()) ? main.ConvertNullDateTime(dr["date_start"]) : null);
                        DateTime? dtEnd = (!string.IsNullOrEmpty(dr["date_end"].ToString()) ? main.ConvertNullDateTime(dr["date_end"]) : null);
                        dbManager.AddParameters(16, "@date_start", (dtStart != null ? (DateTime?)dtStart.Value.AddYears(nDefYear) : null));
                        dbManager.AddParameters(17, "@date_end", (dtEnd != null ? (DateTime?)dtEnd.Value.AddYears(nDefYear) : null));
                        dbManager.AddParameters(18, "@created_by", strEmpSeq);
                        dbManager.AddParameters(19, "@created_when", DateTime.Now);

                        strSQL = "insert into bgm_request"
                            + " (bgm_req_code, bgm_req_name, bgm_req_descr, bgm_req_manager, bgm_req_scope, bgm_req_date"
                            + ", bgm_req_reason, bgm_req_object, bgm_req_target, bgm_req_plan, bgm_req_remark"
                            + ", bgm_strat_list_seq, prj_type_seq, job_site_seq, job_site_seq_main, bgm_year"
                            + ", date_start, date_end, record_status, created_by, created_when)"
                            + " values"
                            + " (@bgm_req_code, @bgm_req_name, @bgm_req_descr, @bgm_req_manager, @bgm_req_scope, @bgm_req_date"
                            + ", @bgm_req_reason, @bgm_req_object, @bgm_req_target, @bgm_req_plan, @bgm_req_remark"
                            + ", @bgm_strat_list_seq, @prj_type_seq, @job_site_seq, @job_site_seq_main, @bgm_year"
                            + ", @date_start, @date_end, 'W', @created_by, @created_when);"
                            + " select scope_identity()";
                        strBgmReqSeq = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0].Rows[0][0].ToString();

                        dbManager.CreateParameters(4);
                        dbManager.AddParameters(0, "@bgm_req_seq", strBgmReqSeq);
                        dbManager.AddParameters(1, "@bgm_req_seq_old", strBgmReqSeqOld);
                        dbManager.AddParameters(2, "@created_by", strEmpSeq);
                        dbManager.AddParameters(3, "@created_when", DateTime.Now);

                        strSQL = "insert into bgm_request_expense"
                            + " (bgm_req_seq, descr, total_amount, remark, mtef1, mtef2, mtef3"
                            + ", bgm_source_seq, bgm_exp_seq, icm_res_item_seq, unit_price, unit_qty"
                            + ", created_by, created_when)"
                            + " (select @bgm_req_seq, descr, total_amount, remark, mtef1, mtef2, mtef3"
                            + ", bgm_source_seq, bgm_exp_seq, icm_res_item_seq, unit_price, unit_qty"
                            + ", @created_by, @created_when"
                            + " from bgm_request_expense"
                            + " where bgm_req_seq = @bgm_req_seq_old"
                            + ")";
                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                        strSQL = "insert into bgm_request_option"
                            + " (bgm_req_seq, descr, weight, bgm_option_seq"
                            + ", created_by, created_when)"
                            + " (select @bgm_req_seq, descr, weight, bgm_option_seq"
                            + ", @created_by, @created_when"
                            + " from bgm_request_option"
                            + " where bgm_req_seq = @bgm_req_seq_old"
                            + ")";
                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);

                        strSQL = "insert into bgm_request_manager"
                            + " (bgm_req_seq, emp_seq, descr)"
                            + " (select @bgm_req_seq, emp_seq, descr"
                            + " from bgm_request_manager"
                            + " where bgm_req_seq = @bgm_req_seq_old"
                            + ")";
                        dbManager.ExecuteNonQuery(CommandType.Text, strSQL);
                    }
                }

                dbManager.CommitTransaction();
                ClosePopup();                
            }
            catch (Exception ex)
            {
                dbManager.RollBackTransaction();
                throw ex;
            }
            finally
            {
                dbManager.Dispose();
            }
        }

        protected void ClosePopup()
        {
            ScriptManager.RegisterClientScriptBlock(
                this.Page,
                this.GetType(),
                "WebUserControlSript",
                "returnToParent()",
                true);
        }

        protected void gridProject_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblCount.Text = "จำนวนโครงการที่คัดลอก " + gridProject.SelectedItems.Count.ToString("#,##0");
        }
    }
}